<template>
	<view class="container">
	  <!-- 状态栏占位 -->
	  <view :style="{ height: statusBarHeight + 'px' }"></view>
	  
	  <!-- 用户信息区域 -->
	      <view class="user-info-section" @click="goToUserDetail">
	        <view class="user-info">
	          <image 
	            class="avatar" 
	            :src="userStore.isLoggedIn ? (BASE_URL+(userStore.userInfo.avatar ) ) : '/static/placeholder.png'" 
	            mode="aspectFill"
	          ></image>
	          <view class="user-detail">
	            <!-- 已登录显示用户信息 -->
	            <template v-if="userStore.isLoggedIn">
	              <view class="user-name">{{ userStore.userInfo.username || '用户' }}</view>
	              <view class="user-id">{{ userStore.userInfo.phone ? `手机号: ${maskPhone(userStore.userInfo.phone)}` : `ID: ${userStore.userInfo.id}` }}</view>
	            </template>
	            <!-- 未登录显示登录按钮 -->
	            <template v-else>
	              <view class="login-btn" @click.stop="handleLogin">点击登录</view>
	              <view class="user-desc">登录后享受更多权益</view>
	            </template>
	          </view>
	        </view>
	        <view class="user-stats">
	          <view class="stat-item">
	            <text class="stat-num">{{ userStats.favorites }}</text>
	            <text class="stat-label">收藏</text>
	          </view>
	          <view class="stat-item">
	            <text class="stat-num">{{ userStats.following }}</text>
	            <text class="stat-label">关注</text>
	          </view>
	          <view class="stat-item">
	            <text class="stat-num">{{ userStats.footprints }}</text>
	            <text class="stat-label">足迹</text>
	          </view>
	        </view>
	      </view>
	     
	  <!-- 我的订单 -->
	  <view class="order-section">
	    <view class="section-header">
	      <text class="section-title">我的订单</text>
	      <view class="view-all" @click="viewAllOrders">
	        <text>查看全部</text>
	        <uni-icons type="right" size="14" color="#999"></uni-icons>
	      </view>
	    </view>
	    <view class="order-types">
	      <view class="order-type-item" @click="viewOrderByType('pending')">
	        <view class="order-icon-wrapper">
	          <uni-icons type="wallet" size="28" color="#FF8C42"></uni-icons>
	          <view v-if="orderCounts.pending > 0" class="order-badge">{{ orderCounts.pending }}</view>
	        </view>
	        <text>待付款</text>
	      </view>
	      <view class="order-type-item" @click="viewOrderByType('shipping')">
	        <view class="order-icon-wrapper">
	          <uni-icons type="shop" size="28" color="#FF8C42"></uni-icons>
	          <view v-if="orderCounts.shipping > 0" class="order-badge">{{ orderCounts.shipping }}</view>
	        </view>
	        <text>待发货</text>
	      </view>
	      <view class="order-type-item" @click="viewOrderByType('receiving')">
	        <view class="order-icon-wrapper">
	          <uni-icons type="home" size="28" color="#FF8C42"></uni-icons>
	          <view v-if="orderCounts.receiving > 0" class="order-badge">{{ orderCounts.receiving }}</view>
	        </view>
	        <text>待收货</text>
	      </view>
	      <view class="order-type-item" @click="viewOrderByType('comment')">
	        <view class="order-icon-wrapper">
	          <uni-icons type="chat" size="28" color="#FF8C42"></uni-icons>
	          <view v-if="orderCounts.comment > 0" class="order-badge">{{ orderCounts.comment }}</view>
	        </view>
	        <text>待评价</text>
	      </view>
	      <view class="order-type-item" @click="viewOrderByType('aftersale')">
	        <view class="order-icon-wrapper">
	          <uni-icons type="refresh" size="28" color="#FF8C42"></uni-icons>
	          <view v-if="orderCounts.aftersale > 0" class="order-badge">{{ orderCounts.aftersale }}</view>
	        </view>
	        <text>退换/售后</text>
	      </view>
	    </view>
	  </view>
	     
	  <!-- 我的服务 -->
	  <view class="service-section">
	    <view class="section-header">
	      <text class="section-title">我的服务</text>
	    </view>
	    <view class="service-grid">
	      <view class="service-item" @click="goToService('address')">
	        <uni-icons type="location" size="24" color="#FF8C42"></uni-icons>
	        <text>收货地址</text>
	      </view>
	      <view class="service-item" @click="goToService('coupon')">
	        <uni-icons type="gift" size="24" color="#FF8C42"></uni-icons>
	        <text>优惠券</text>
	      </view>
	      <view class="service-item" @click="goToService('customer')">
	        <uni-icons type="headphones" size="24" color="#FF8C42"></uni-icons>
	        <text>客服中心</text>
	      </view>
	      <view class="service-item" @click="goToService('feedback')">
	        <uni-icons type="help" size="24" color="#FF8C42"></uni-icons>
	        <text>意见反馈</text>
	      </view>
	      <view class="service-item" @click="goToService('about')">
	        <uni-icons type="info" size="24" color="#FF8C42"></uni-icons>
	        <text>关于我们</text>
	      </view>
	      <view class="service-item" @click="goToService('settings')">
	        <uni-icons type="gear" size="24" color="#FF8C42"></uni-icons>
	        <text>设置</text>
	      </view>
	    </view>
	  </view>
	  
	  <!-- 退出登录按钮 (仅在登录状态显示) -->
	  <view v-if="userStore.isLoggedIn" class="logout-section">
	    <button class="logout-btn" @click="handleLogout">退出登录</button>
	  </view>
	  
	  <!-- 登录弹窗 -->
	  <login-popup ref="loginPopupRef"></login-popup>
	  
	  <!-- 用户类型管理 -->
	  <user-type-manager></user-type-manager>
	  
	  <!-- 底部导航栏 -->
	  <tab-bar :active="2"></tab-bar>
</view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useUserStore } from '@/store/user';
import UserTypeManager from '@/components/user-type-manager.vue';
import TabBar from '@/components/tab-bar.vue';
import LoginPopup from '@/components/login-popup.vue';
import { BASE_URL } from '@/config/env';
import http from '@/utils/http/http.js';
import { onShow } from '@dcloudio/uni-app';

const userStore = useUserStore();
const statusBarHeight = ref(0);
const loginPopupRef = ref(null);

// 用户统计数据
const userStats = ref({
  favorites: 0,
  following: 0,
  footprints: 0
});

// 订单数量统计
const orderCounts = ref({
  pending: 0,    // 待付款
  shipping: 0,   // 待发货
  receiving: 0,  // 待收货
  comment: 0,    // 待评价
  aftersale: 0   // 退换/售后
});

// 订单状态映射
const orderStatusMap = {
  'pending': 0,    // 待付款
  'shipping': 1,   // 待发货
  'receiving': 2,  // 待收货
  'comment': 3,    // 待评价 (已完成但未评价)
  'aftersale': 5   // 退换/售后
};

// 获取状态栏高度
const getStatusBarHeight = () => {
  let systemInfo;
  try {
    systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
    console.log('状态栏高度:', statusBarHeight.value);
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 手机号码脱敏
const maskPhone = (phone) => {
  if (!phone || phone.length < 11) return phone;
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

// 简化订单数量统计 - 不依赖后端接口
const updateOrderCounts = () => {
  // 由于后端没有提供订单统计接口，这里使用默认值
  // 实际项目中可以通过获取订单列表来计算数量
  if (!userStore.isLoggedIn) {
    orderCounts.value = {
      pending: 0,
      shipping: 0,
      receiving: 0,
      comment: 0,
      aftersale: 0
    };
  } else {
    // 可以在这里调用订单列表接口来计算各状态数量
    // 为了简化，暂时不显示具体数量
    orderCounts.value = {
      pending: 0,
      shipping: 0,
      receiving: 0,
      comment: 0,
      aftersale: 0
    };
  }
};

// 简化用户统计 - 使用默认值
const updateUserStats = () => {
  if (!userStore.isLoggedIn) {
    userStats.value = {
      favorites: 0,
      following: 0,
      footprints: 0
    };
  } else {
    // 由于后端没有提供用户统计接口，使用默认值
    userStats.value = {
      favorites: 0,
      following: 0,
      footprints: 0
    };
  }
};

// 处理登录点击
const handleLogin = () => {
  console.log('用户点击登录按钮');
  if (loginPopupRef.value) {
    loginPopupRef.value.open();
  } else {
    console.error('登录弹窗组件未找到');
    uni.showToast({
      title: '登录功能暂不可用',
      icon: 'none'
    });
  }
};

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确认退出登录？',
    success: (res) => {
      if (res.confirm) {
        userStore.logout();
        // 重置统计数据
        orderCounts.value = {
          pending: 0,
          shipping: 0,
          receiving: 0,
          comment: 0,
          aftersale: 0
        };
        userStats.value = {
          favorites: 0,
          following: 0,
          footprints: 0
        };
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        });
      }
    }
  });
};
//console.log("userStore.userInfo",userStore.userInfo);
// 查看全部订单
const viewAllOrders = () => {
  // 检查是否登录
  if (!userStore.isLoggedIn) {
    handleLogin();
    return;
  }
  
  // 跳转到订单列表页面
  uni.navigateTo({
    url: '/pages/orders/order-list'
  });
};

// 按类型查看订单 - 更新实现
const viewOrderByType = (type) => {
  // 检查是否登录
  if (!userStore.isLoggedIn) {
    handleLogin();
    return;
  }
  
  // 获取对应的status值，与后端OrderController保持一致
  let status = null;
  
  switch (type) {
    case 'pending':
      status = 0; // 待付款
      break;
    case 'shipping':
      status = 1; // 待发货
      break;
    case 'receiving':
      status = 2; // 待收货
      break;
    case 'comment':
      status = 3; // 已完成(待评价)
      break;
    case 'aftersale':
      // 退换/售后功能开发中
      uni.showToast({
        title: '退换/售后功能开发中',
        icon: 'none'
      });
      return;
  }
  
  // 跳转到订单列表页面，传递status参数
  uni.navigateTo({
    url: `/pages/orders/order-list?status=${status}`
  });
};

// 跳转到用户详情页面
const goToUserDetail = () => {
  // 检查是否登录
  if (!userStore.isLoggedIn) {
    handleLogin();
    return;
  }
  
  // 跳转到用户详情页面
  uni.navigateTo({
    url: `/pages/user/detail?id=${userStore.userInfo.id}`
  });
};

// 跳转到服务页面
const goToService = (service) => {
  // 某些服务可能需要登录
  if (['address', 'coupon'].includes(service) && !userStore.isLoggedIn) {
    handleLogin();
    return;
  }
  
  // 处理收货地址
  if (service === 'address') {
    uni.navigateTo({
      url: '/pages/address/address-list'
    });
    return;
  }
  // 处理设置
  if (service === 'settings') {
    // 跳转到用户详情页面
    uni.navigateTo({
      url: `/pages/user/detail?id=${userStore.userInfo.id}`
    });
    return;
  }
  // 处理优惠卷
  if (service === 'coupon') {
    uni.navigateTo({
      url: '/pages/service/coupon'
    });
    return;
  }
  // 处理客服中心
  if (service === 'customer') {
    uni.navigateTo({
      url: '/pages/service/customer'
    });
    return;
  }
  // 处理反馈
  if (service === 'feedback') {
    uni.navigateTo({
      url: '/pages/service/feedback'
    });
	return;
	}
	// 处理关于我们
	if (service === 'about') {
	  uni.navigateTo({
	    url: '/pages/service/about'
	  });
    return;
  }
  uni.showToast({
    title: `${service}功能等待后端接口`,
    icon: 'none'
  });
};

// 监听用户登录状态变化
watch(() => userStore.isLoggedIn, (newValue) => {
  if (newValue) {
    // 用户登录后更新统计数据
    updateOrderCounts();
    updateUserStats();
  } else {
    // 用户退出登录后重置数据
    orderCounts.value = {
      pending: 0,
      shipping: 0,
      receiving: 0,
      comment: 0,
      aftersale: 0
    };
    userStats.value = {
      favorites: 0,
      following: 0,
      footprints: 0
    };
  }
});

// 页面加载时执行
onMounted(() => {
  console.log('个人中心页面加载完成');
  // 初始化用户状态
  userStore.initUserState();
  // 获取状态栏高度
  getStatusBarHeight();
  // 如果已登录，更新统计数据
  if (userStore.isLoggedIn) {
    updateOrderCounts();
    updateUserStats();
  }
});

// 页面显示时刷新数据
onShow(() => {
  console.log('个人中心页面显示');
  // 重新初始化用户状态
  userStore.initUserState();
  // 如果已登录，刷新统计数据
  if (userStore.isLoggedIn) {
    updateOrderCounts();
    updateUserStats();
  }
});
</script>

<style>
.container {
  padding-bottom: 100rpx;
  background-color: #FFF9F2;
}

.user-info-section {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  padding: 40rpx 30rpx;
  color: #fff;
  border-radius: 0 0 30rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.2);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background-color: #fff;
  margin-right: 30rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.login-btn {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.user-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 16rpx;
  padding: 20rpx 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-num {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 6rpx;
}

.stat-label {
  font-size: 24rpx;
}

.order-section, .service-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #FFE6CC;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #FF8C42;
  border-radius: 3rpx;
}

.view-all {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}

.order-types {
  display: flex;
  padding: 30rpx 0;
}

.order-type-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.3s ease;
}

.order-type-item:active {
  transform: scale(0.95);
}

.order-icon-wrapper {
  position: relative;
  margin-bottom: 10rpx;
}

.order-badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  background-color: #FF4444;
  color: #fff;
  font-size: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
  box-shadow: 0 2rpx 4rpx rgba(255, 68, 68, 0.3);
}

.order-type-item text {
  font-size: 24rpx;
  color: #666;
}

.service-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.service-item {
  width: 33.33%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  transition: transform 0.3s ease;
}

.service-item:active {
  transform: scale(0.95);
}

.service-item text {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #666;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.user-id {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 退出登录按钮 */
.logout-section {
  padding: 30rpx 20rpx;
}

.logout-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  color: #FF8C42;
  background-color: #fff;
  border: 1rpx solid #FF8C42;
  border-radius: 40rpx;
  transition: all 0.3s ease;
}

.logout-btn:active {
  background-color: #FFF0E0;
}
</style>
